const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
};



// 根据code 转换为openid
function code_transition_openid(){
    // 说明已获取到用户的微信基本信息
    var wx_base_info = wx.getStorageSync('wx_base_info')
    var that = this
    var app = getApp()
    // 登录
    wx.login({
        success: res => {
            // console.log(res)
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            wx.request({
                url: app.globalData.class_api_url + '&do=bookapi&op=get_wx_open_info&code=' + res.code,
                header: {
                    'content-type': 'application/josn'
                },
                success: function (data) {
                    // 获取openid
                    data = JSON.parse(data.data)
                    wx.request({
                        url: app.globalData.class_api_url + '&do=bookapi&op=get_user_info',
                        header: {
                            "content-type": "application/x-www-form-urlencoded"
                        },
                        data: {
                            wx_headimg: wx_base_info.avatarUrl,
                            wxid: data.openid,
                            gender: wx_base_info.gender,
                            wx_nick_name: wx_base_info.nickName
                        },
                        method: 'POST',
                        success: function (res) {
                            // 获取到数据库用户信息
                            // console.log(res)
                            wx.setStorage({
                                key: 'user_info',
                                data: res.data,
                                success: function () {
                                    // console.log('保存用户信息到本地成功！')
                                },
                                fail:function(){
                                    console.log('保存用户信息到本地失败！')
                                }
                            })
                        }
                    })


                }
            })

        },
        fail: function () {
            console.log('登陆失败' + res.errMsg)
        }
    });
}


//检测是否登陆
function check_for_lgoin(){
    wx.setStorage({
        key: 'wx_base_info',
        data: res.detail.userInfo,
        success: function () {
            console.log('已登录')
        },
        fail:function(){
            console.log('未登录')
        }
    })
}

module.exports = {
    formatTime: formatTime,
    code_transition_openid: code_transition_openid,
    check_for_lgoin: check_for_lgoin
}


